package com.yupi.springbootinit.utils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author 28993
 */
@Slf4j
public class ExcelUtils {


	/**
	 * 将数据装换成CSV格式的数据
	 * 因为我们要根据每天的数据进行分析,所以每天的数据在被读取之后
	 * 不嫩因为Map集合乱序了 所以这里我们使用LinkedHashMap
	 * CSV数据格式: 姓名,年龄,地址,小花,12,北京,小明,45，上海
	 */
	public static String readExcelDataToCsv(MultipartFile multipartFile) throws IOException {
		List<LinkedHashMap<Integer,String>> list = null;

		try {
			list = EasyExcel.read(multipartFile.getInputStream())
					.excelType(ExcelTypeEnum.XLSX)
					.sheet()
					.headRowNumber(0)
					.doReadSync();
		} catch (Exception e) {
			log.error("处理异常"+e);
			e.printStackTrace();
		}
		if (CollUtil.isEmpty(list)) {
			return "";
		}
		//先拿到表头数据
		LinkedHashMap<Integer, String> linkedHashMap = list.get(0);
		StringBuilder stringBuilder = new StringBuilder();
		List<String> collect = linkedHashMap.values().stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
		stringBuilder.append(StringUtils.join(collect,",")).append("\n");
		// 读取数据
		for (int i = 1; i < list.size(); i++) {
			LinkedHashMap<Integer, String> dataMap = list.get(i);
			List<String> dataList = dataMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
			//补上\n再输出数据时会遇到\n就换行输出
			stringBuilder.append(StringUtils.join(dataList, ",")).append("\n");
		}
		return stringBuilder.toString();
	}

	public static void main(String[] args) throws IOException {

		ClassPathResource classPathResource = new ClassPathResource("tubiao.xlsx");
		InputStream inputStream = classPathResource.getInputStream();
	}

	/**
	 * 以MultiFile的方式读取 前端 上传的excel文件，而后保存数据库
	 */


	public List<T> ReaderMultiFileExcel(Class<T> type, MultipartFile multipartFile) throws IOException {
		InputStream inputStream = multipartFile.getInputStream();
		List<T> object = EasyExcel.read(inputStream).head(type).sheet().doReadSync();
		return object;
	}
}
